package com.okq.util.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 描述 : session过滤器
 * 作者 : zdl
 * 日期 : 2017/3/15 13:23
 */
public class SessionFilter implements Filter {

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        String requestURL = request.getRequestURI().toUpperCase();
        String ctxPath = request.getContextPath();
        String filename = requestURL.substring(requestURL.lastIndexOf("/") + 1, requestURL.length());

        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + ctxPath + "/";

        HttpSession session = request.getSession();
        if (requestURL.contains("ANDROID")) {
            chain.doFilter(req, res);
        } else {
            if (filename.endsWith("JSP") || filename.endsWith("ACTION")) {
                if (filename.equalsIgnoreCase("LOGIN.JSP")
                        || filename.equalsIgnoreCase("LOGIN.ACTION")
                        || filename.equalsIgnoreCase("LOGOUT.JSP")
                        || filename.equalsIgnoreCase("CODE.JSP")
                        || filename.equalsIgnoreCase("TRACE.JSP")
                        || filename.equalsIgnoreCase("SEARCH.ACTION")
                        || filename.equalsIgnoreCase("J_SPRING_SECURITY_CHECK.ACTION")) {
                    chain.doFilter(req, res);
                } else {
                    if (session.getAttribute("loginUser") == null) {
                        response.sendRedirect(basePath + "login.jsp?redirect=login");
                    } else {
                        chain.doFilter(req, res);
                    }
                }
            } else {
                chain.doFilter(req, res);
            }
        }


    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}
